package com.vcg.comment.support.clean.utils;

import java.security.KeyFactory;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by wuyu on 2016/5/31.
 */
public class SignVerify {

    public String sign(String privateKeyStr, String content) {
        try {
            byte[] e = Base64.decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(e);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKey privateKey = (RSAPrivateKey)keyFactory.generatePrivate(keySpec);
            Signature signer = Signature.getInstance("SHA1WithRSA");
            signer.initSign(privateKey);
            signer.update(content.getBytes());
            byte[] signed = signer.sign();
            return new String(Base64.encode(signed));
        } catch (Exception var9) {
            return "err";
        }
    }

    public boolean verify(String publicKeyStr, String sign, String content) {
        try {
            byte[] e = Base64.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(e);
            RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
            Signature signer = Signature.getInstance("SHA1WithRSA");
            signer.initVerify(pubKey);
            signer.update(content.getBytes());
            return signer.verify(Base64.decode(sign));
        } catch (Exception var9) {
            return false;
        }
    }
}
